from widgets.scriptWidgets.ScriptWidget import ScriptWidget
from enums.WidgetType import WidgetType
from PySide6.QtWidgets import QLabel, QPushButton, QFileDialog
from PySide6.QtGui import QPixmap
from PIL import ImageGrab, ImageQt
from ..ScriptInput import ScriptInput
from util.Mouse import MouseUtil
import shutil
import os.path as ospath
from config import config
import time


class WaitPic(ScriptWidget):
    def __init__(self, initType=None):
        super(WaitPic, self).__init__(WidgetType.WAIT_PIC)

        self.picPath = ospath.join(
            config.SCRIPT_PIC_RECOGNITION_PIC_PATH,
            str(int(round(time.time() * 1000))) + '.png'
        )

        self.labTitle = QLabel('等待图片:', self)
        self.labTitle.setFixedSize(55, self.lineHeight)
        self.addWidget(self.labTitle)

        self.newLineSpaceWidth = self.labTitle.width() + self.intervalX

        # x
        self.inputX = ScriptInput(self, 'x')
        self.inputX.text = 0
        self.addWidget(self.inputX)

        # y
        self.inputY = ScriptInput(self, 'y')
        self.inputY.text = 0
        self.addWidget(self.inputY)

        if initType == 'edit' or initType == 'create':
            self.addOperate()

        self.newLine()
        # 宽
        self.inputWidth = ScriptInput(self, '宽')
        self.inputWidth.text = 0
        self.addWidget(self.inputWidth)

        # 高
        self.inputHeight = ScriptInput(self, '高')
        self.inputHeight.text = 0
        self.addWidget(self.inputHeight)

        self.btnTrack = QPushButton(self)
        self.btnTrack.setText('选择区域')
        self.btnTrack.clicked.connect(self.chooseArea)
        self.addWidget(self.btnTrack)

        self.newLine()
        # 图片
        self.labImgTitle = QLabel('图片', self)
        self.labImgTitle.setFixedSize(30, self.lineHeight)
        self.addWidget(self.labImgTitle)

        self.labImg = QLabel(self)
        self.labImg.setFixedSize(self.lineHeight, self.lineHeight)
        self.labImg.setStyleSheet(
            "QLabel{background:white;}"
        )
        self.addWidget(self.labImg)

        self.btnChoosePic = QPushButton(self)
        self.btnChoosePic.setText('选择图片')
        self.btnChoosePic.clicked.connect(self.choosePic)
        self.addWidget(self.btnChoosePic)

        self.btnGrab = QPushButton(self)
        self.btnGrab.setText('截取屏幕')
        self.btnGrab.clicked.connect(self.startGrab)
        self.addWidget(self.btnGrab)

    def onMouseClick(self, x, y, width, height, button):
        self.inputX.text = int(x)
        self.inputY.text = int(y)
        self.inputWidth.text = width
        self.inputHeight.text = height

    def chooseArea(self):
        MouseUtil.listenArea(self.onMouseClick)

    def choosePic(self):
        imgName, imgType = QFileDialog.getOpenFileName(
            self, "选择图片", "",
            "Image Files (*.png *.jpeg *.bmp);;All Files(*)")
        if imgName is None:
            return

        # 将需要识别的图片保存到应用内部存储地址
        shutil.copy(imgName, self.picPath)

        self.labImg.setPixmap(QPixmap(imgName).scaled(self.labImg.width(), self.labImg.height()))

    def onMouseClick(self, x, y, width, height, button):
        self.inputX.text = int(x)
        self.inputY.text = int(y)
        self.inputWidth.text = width
        self.inputHeight.text = height

    def startAreaChoose(self):
        MouseUtil.listenArea(self.onMouseClick)

    def grabScreen(self, x, y, width, height, button):
        left = x
        top = y
        right = x + width
        bottom = y + height
        # 将需要识别的图片保存到应用内部存储地址
        recoImg = ImageGrab.grab(bbox=(left, top, right, bottom))
        recoImg.save(self.picPath)
        self.labImg.setPixmap(ImageQt.toqpixmap(recoImg))

    def startGrab(self):
        MouseUtil.listenArea(self.grabScreen)

    @property
    def data(self):
        return {
            'type': self.type.value,
            'x': int(self.inputX.text),
            'y': int(self.inputY.text),
            'width': int(self.inputWidth.text),
            'height': int(self.inputHeight.text),
            'pic': self.picPath,
            'enable': self.switchEnable.isChecked()
        }

    @data.setter
    def data(self, data):
        self.inputX.text = str(data['x'])
        self.inputY.text = str(data['y'])
        self.inputWidth.text = str(data['width'])
        self.inputHeight.text = str(data['height'])
        self.labImg.setPixmap(QPixmap(data['pic']))
        self.picPath = data['pic']
